/**
 * Copyright (c) 2006-2016 Huize Ltd. All Rights Reserved. 
 *  
 * This code is the confidential and proprietary information of   
 * Hzins. You shall not disclose such Confidential Information   
 * and shall use it only in accordance with the terms of the agreements   
 * you entered into with Huize,http://www.huize.com.
 *  
 */
package com.agan.concurrent;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hz1412988
 * @date 2018年2月8日 下午4:46:12
 * @version
 */
public class PrimeGenerator implements Runnable {

    private final List<BigInteger> primes = new ArrayList<BigInteger>();

    // 注意使用volatile关键字，保证可见性
    private volatile boolean cancelled;

    public void run() {
	BigInteger p = BigInteger.ONE;
	while (!cancelled) {
	    p = p.nextProbablePrime();
	    synchronized (this) {
		primes.add(p);
	    }
	}
    }

    public void cancel() {
	cancelled = true;
    }

    public synchronized List<BigInteger> get() {
	return new ArrayList<BigInteger>(primes);
    }
}
